package com.hengpeng.itfin.persist.impl;

import java.util.Date;
import java.util.List;

import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Repository;

import com.hengpeng.common.persist.AbstractDao;
import com.hengpeng.common.persist.entity.AbstractEntity.BoolValue;
import com.hengpeng.common.persist.query.DynamicQuery;
import com.hengpeng.common.persist.query.Projections;
import com.hengpeng.common.persist.query.constants.QueryConstants.LockType;
import com.hengpeng.common.util.DateTimeUtil;
import com.hengpeng.itfin.persist.RepaymentPlanDao;
import com.hengpeng.itfinbase.persist.RepaymentPlan;
import com.hengpeng.itfinbase.persist.RepaymentPlan.ReplaymentStatus;

@Repository
@Lazy
public class RepaymentPlanDaoImpl extends AbstractDao<RepaymentPlan> implements RepaymentPlanDao
{
	@Override
	public List<RepaymentPlan> getOverdureList()
	{
		DynamicQuery query = new DynamicQuery(RepaymentPlan.class);
		query.eq("isOverDured", BoolValue.NO);
		query.eq("status", ReplaymentStatus.UNSETTLE);
		query.le("lastRepayDate", DateTimeUtil.addDate(DateTimeUtil.getSomeDayStartTimes(new Date()), 1));
		return super.findAllByDynamicQuery(query);
	}

	@Override
	public long countRepayPlan(Long borrowId, ReplaymentStatus[] status)
	{
		DynamicQuery query = new DynamicQuery(RepaymentPlan.class);
		query.addProjection(Projections.count());
		if (borrowId != null)
		{
			query.eq("borrowinfoId", borrowId);
		}
		if (status != null && status.length > 0)
		{
			query.inArray("status", status);
		}
		return super.countByDynamicQuery(query);
	}

	@Override
	public List<RepaymentPlan> lockList(Long borrowInfoId, Integer curRecNum, ReplaymentStatus[] status)
	{
		DynamicQuery query = new DynamicQuery(RepaymentPlan.class);
		if (borrowInfoId != null)
		{
			query.eq("borrowinfoId", borrowInfoId);
		}
		if (curRecNum != null)
		{
			query.eq("curRepayNum", curRecNum);
		}
		if (status != null && status.length > 0)
		{
			query.inArray("status", status);
		}
		return super.findAllByDynamicQuery(query, LockType.LOCK_WAIT);
	}

	@Override
	public void updatePlans(List<RepaymentPlan> plans)
	{
		super.updateAll(plans);
	}

	@Override
	public void savePlans(List<RepaymentPlan> plans)
	{
		super.saveAll(plans);
	}

	@Override
	public int updateStatus(Long borrowInfoId, ReplaymentStatus newStatus,
			ReplaymentStatus oldStatus, Date repayTime, Date updateTime,
			int curRepayNum) {
		return super.exeNamedQuery("repaymentPlan.updateStatus", new Object[] {newStatus,repayTime,updateTime, borrowInfoId,curRepayNum,oldStatus});
	}
	
	
}
